﻿using System;
using System.IO;
using System.Web;
using System.Text;

namespace Ehai.Web.Framework.Rules
{
    class DownFileRuleHandle : IMsgRuleHandle
    {
        #region IMsgRuleHandle 成员

#if DEBUG

        private int _execStatus = 0;
        public int ExecStatus
        {
            get { return _execStatus; }
        }

#endif

        public const string Name = "downfile";


        #region 下载文件

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="p">
        /// 下载的参数，一维数组：
        /// 0：(必选)downFile
        /// 1：(必选)要下载的文件的路径（网站地址）
        /// 2：(必选)网站的地址，如：http://202.204.222.111/Web
        /// 3：(必选)网站地址对应的绝对路径，如:C:\wwwroot
        /// 4：(必选)是否删除传输后的文件，指定true（删除)或false
        /// </param>
        /// <param name="ci">环境变量</param>
        /// <example>示例代码</example>
        /// <code>
        /// Execute(new string[5] { "downFile", "http://202.204.222.111/Web/a/1.txt", @"http://202.204.222.111/Web/", @"D:\temp\", "true" },ci);
        /// </code>
        /// <exception cref="Ehai.Web.Framework.WebException">
        /// Ehai.Web.Framework.Rules.downFile", "下载过程失败！
        /// </exception>
        /// <returns>返回值永远是null</returns>

        public string[][] Execute(string[] p, ContextInfo ci)
        {

            if (p.Length < 5)
            {

#if DEBUG
                _execStatus = -2;
#endif

                return null;
            }
            if (p[1] == null)
            {
#if DEBUG
                _execStatus = 1;
#endif

                return null;
            }

            if (p[2] == null)
            {
#if DEBUG
                _execStatus = 2;
#endif

                return null;
            }

            if (p[3] == null)
            {
#if DEBUG
                _execStatus = 3;
#endif

                return null;
            }

            if (p[4] == null)
            {
#if DEBUG
                _execStatus = 4;
#endif

                return null;
            }
            p[2] = p[2].TrimEnd(@"/".ToCharArray());
            p[3] = p[3].TrimEnd(@"\".ToCharArray());
            string filepath = p[1].Replace(p[2], p[3]).Replace("/", @"\");
            string filename = System.IO.Path.GetFileName(filepath);
            bool ifDel = false;
            System.IO.Stream iStream = null;
            int length;
            byte[] buffer;
            long dataToRead;

            try
            {
                ifDel = bool.Parse(p[4]);
                FileInfo fi = new FileInfo(filepath);
                int blen = (int)((fi.Length > 10000) ? 10000 : fi.Length);
                buffer = new Byte[blen];

                iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);

                dataToRead = iStream.Length;
                ci.Response.ContentType = "application/octet-stream";
                ci.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, Encoding.UTF8));

                while (dataToRead > 0)

                    if (ci.Response.IsClientConnected)
                    {

                        length = iStream.Read(buffer, 0, blen);
                        ci.Response.OutputStream.Write(buffer, 0, length);
                        ci.Response.Flush();
                        buffer = new Byte[blen];
                        dataToRead = dataToRead - length;
                    }
                    else
                        dataToRead = -1;

#if DEBUG
                _execStatus = 0;
#endif

            }
            catch (Exception e)
            {

#if DEBUG
                _execStatus = -1;
#endif

                throw new Ehai.Web.Framework.WebException("Ehai.Web.Framework.Rules.downFile", "下载过程失败！", e);
            }
            finally
            {
                if (iStream != null)
                {
                    buffer = null;
                    iStream.Close();
                    iStream.Dispose();
                    if (ifDel)
                        File.Delete(filepath);
                }
            }

            return null;
        }
        #endregion

        public string GetHelpInfo()
        {
            return "下载文件";
        }

        public string GetHelpDetail()
        {
            return "下载文件.参数范例：{ downFile, http://202.204.222.111/Web/a/1.txt, http://202.204.222.111/Web/, D:/temp/, true}";
        }

        public string[] GetParametersInfo()
        {
            string[] t = new string[5];
            t[0] = "[0]操作类型downfile";
            t[1] = "[1]要下载的文件的路径（网站地址）";
            t[2] = "[2]网站的地址，如：http://202.204.222.111/Web";
            t[3] = "[3]网站地址对应的绝对路径，如:C:\\wwwroot";
            t[4] = "[4]是否删除传输后的文件，指定true（删除)或false";
            return t;
        }

        #endregion
    }
}
